<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%" class="account-form-dialog">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="180px"
        v-loading="formLoading"
        class="account-form"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <Icon icon="ep:info-filled" class="section-icon" />
            <span>基本信息</span>
          </div>

          <el-form-item label="渠道" prop="channelId" class="form-item">
            <el-select
              v-model="formData.channelId"
              clearable
              placeholder="请选择渠道"
              :loading="remoteLoading"
              @change="handleQuery"
              class="form-select"
            >
              <el-option
                v-for="item in channelList"
                :key="item.id"
                :label="item.name"
                :value="item.id!"
              >
                <div class="option-item">
                  <Icon icon="ep:connection" class="option-icon" />
                  <span>{{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
            <div class="input-tip">
              <Icon icon="ep:info-filled" class="tip-icon" />
              <span>选择广告账户所属的渠道平台</span>
            </div>
          </el-form-item>

          <el-form-item label="账户名称" prop="name" class="form-item">
            <el-input
              v-model="formData.name"
              placeholder="请输入账户名称"
              class="form-input"
              clearable
              maxlength="50"
            >
              <template #prefix>
                <Icon icon="ep:user" class="input-icon" />
              </template>
            </el-input>
            <div class="input-tip">
              <Icon icon="ep:info-filled" class="tip-icon" />
              <span>为广告账户设置一个易于识别的名称</span>
            </div>
          </el-form-item>
        </div>

        <!-- 授权配置区域 -->
        <div class="form-section">
          <div class="section-title">
            <Icon icon="ep:key" class="section-icon" />
            <span>授权配置</span>
          </div>

          <el-form-item label="授权方式" class="form-item">
            <el-radio-group v-model="formData.authType" class="auth-radio-group">
              <el-radio :label="1" class="auth-radio">
                <div class="radio-content">
                  <Icon icon="ep:platform" class="radio-icon" />
                  <div class="radio-text">
                    <span class="radio-label">自有开放平台授权</span>
                    <span class="radio-desc">使用自己的开放平台账户进行授权</span>
                  </div>
                </div>
              </el-radio>
              <el-radio :label="2" class="auth-radio">
                <div class="radio-content">
                  <Icon icon="ep:user-filled" class="radio-icon" />
                  <div class="radio-text">
                    <span class="radio-label">CRM代理授权</span>
                    <span class="radio-desc">通过CRM系统代理进行授权</span>
                  </div>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="formData.authType == 1">
            <el-form-item label="广告账户/商户ID" prop="accountId" class="form-item">
              <el-input
                v-model="formData.accountId"
                placeholder="请输入广告账户/商户ID"
                class="form-input"
                clearable
              >
                <template #prefix>
                  <Icon icon="ep:key" class="input-icon" />
                </template>
              </el-input>
              <div class="input-tip">
                <Icon icon="ep:info-filled" class="tip-icon" />
                <span>从广告平台获取的账户或商户唯一标识</span>
              </div>
            </el-form-item>

            <el-form-item label="APIKEY" prop="apiKey" class="form-item">
              <el-input
                v-model="formData.apiKey"
                placeholder="请输入APIKEY"
                class="form-input"
                clearable
              >
                <template #prefix>
                  <Icon icon="ep:key" class="input-icon" />
                </template>
              </el-input>
              <div class="input-tip">
                <Icon icon="ep:info-filled" class="tip-icon" />
                <span>用于API调用的公钥标识</span>
              </div>
            </el-form-item>

            <el-form-item label="API密钥" prop="apiSecret" class="form-item">
              <el-input
                v-model="formData.apiSecret"
                placeholder="请输入API密钥"
                class="form-input"
                show-password
                clearable
              >
                <template #prefix>
                  <Icon icon="ep:hide" class="input-icon" />
                </template>
              </el-input>
              <div class="input-tip warning">
                <Icon icon="ep:warning" class="tip-icon" />
                <span>API密钥是敏感信息，请妥善保管</span>
              </div>
            </el-form-item>
          </template>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button class="cancel-btn" @click="dialogVisible = false">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button
          type="primary"
          class="submit-btn"
          :disabled="formLoading"
          :loading="formLoading"
          @click="submitForm"
        >
          <Icon icon="ep:check" class="btn-icon" v-if="!formLoading" />
          {{ formLoading ? '提交中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as AccountApi from '@/api/ad/account'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  channelId: undefined,
  name: undefined,
  accountId: undefined,
  apiKey: undefined,
  apiSecret: undefined,
  authType: 1
})
const formRules = reactive({
  channelId: [
    {
      required: true,
      message: '渠道不能为空',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '账户名称不能为空',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
const channelList = ref([])
/** 打开弹窗 */
const open = async (type: string, getChannelList: Array, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  console.log(channelList)
  channelList.value = getChannelList
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AccountApi.getAccount(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AccountApi.AccountVO
    if (formType.value === 'create') {
      await AccountApi.createAccount(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountApi.updateAccount(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    channelId: undefined,
    name: undefined,
    accountId: undefined,
    apiKey: undefined,
    apiSecret: undefined,
    authType: 1
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
// 对话框样式
.account-form-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;

    .el-dialog__header {
      background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
      color: white;
      padding: 20px 24px;

      .el-dialog__title {
        color: white;
        font-size: 18px;
        font-weight: 600;
      }

      .el-dialog__headerbtn {
        .el-dialog__close {
          color: rgba(255, 255, 255, 0.8);
          font-size: 18px;

          &:hover {
            color: white;
          }
        }
      }
    }

    .el-dialog__body {
      padding: 0;
    }

    .el-dialog__footer {
      padding: 0;
      border-top: 1px solid #f1f5f9;
    }
  }
}

// 表单容器
.form-container {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.account-form {
  .form-section {
    margin-bottom: 32px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 区域标题
.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f1f5f9;

  .section-icon {
    color: #0052cc;
    font-size: 18px;
  }

  span {
    font-size: 16px;
    font-weight: 600;
    color: #374151;
  }
}

// 表单项
.form-item {
  margin-bottom: 24px;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
    line-height: 1.6;
  }

  :deep(.el-form-item__content) {
    line-height: normal;
  }
}

// 输入框样式
.form-input {
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      border-color: #d1d5db;
    }

    &.is-focus {
      border-color: #0052cc;
      box-shadow: 0 0 0 3px rgba(0, 82, 204, 0.1);
    }
  }

  .input-icon {
    color: #9ca3af;
    font-size: 16px;
  }
}

// 选择框样式
.form-select {
  width: 100%;

  :deep(.el-select__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      border-color: #d1d5db;
    }

    &.is-focused {
      border-color: #0052cc;
      box-shadow: 0 0 0 3px rgba(0, 82, 204, 0.1);
    }
  }
}

// 选项样式
.option-item {
  display: flex;
  align-items: center;
  gap: 8px;

  .option-icon {
    font-size: 14px;
    color: #6b7280;
  }
}

// 单选框组样式
.auth-radio-group {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .auth-radio {
    margin: 0;
    padding: 16px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    transition: all 0.3s ease;
    width: 250px;
    &:hover {
      border-color: #d1d5db;
      background: #f8fafc;
    }

    :deep(.el-radio__input.is-checked) {
      .el-radio__inner {
        background-color: #0052cc;
        border-color: #0052cc;
      }
    }

    &.is-checked {
      border-color: #0052cc;
      background: rgba(0, 82, 204, 0.05);
    }
  }
}

.radio-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-left: 24px;

  .radio-icon {
    color: #6b7280;
    font-size: 20px;
    margin-top: 2px;
    flex-shrink: 0;
  }

  .radio-text {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .radio-label {
      font-weight: 500;
      color: #374151;
      font-size: 14px;
    }

    .radio-desc {
      font-size: 12px;
      color: #6b7280;
      line-height: 1.4;
    }
  }
}

// 输入提示
.input-tip {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-top: 8px;
  padding: 12px;
  background: #f0f9ff;
  border: 1px solid #e0f2fe;
  border-radius: 8px;

  .tip-icon {
    color: #0ea5e9;
    font-size: 16px;
    margin-top: 2px;
    flex-shrink: 0;
  }

  span {
    font-size: 13px;
    color: #0369a1;
    line-height: 1.4;
  }

  &.warning {
    background: #fef3c7;
    border-color: #fbbf24;

    .tip-icon {
      color: #f59e0b;
    }

    span {
      color: #92400e;
    }
  }
}

// 对话框底部
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: #f8fafc;
}

.cancel-btn {
  padding: 10px 20px;
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  background: white;
  color: #6b7280;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    margin-right: 6px;
    font-size: 14px;
  }

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }
}

.submit-btn {
  padding: 10px 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  border: none;
  color: white;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    margin-right: 6px;
    font-size: 14px;
  }

  &:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

// H5 响应式设计
@media (max-width: 768px) {
  .account-form-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 20px auto;

      .el-dialog__header {
        padding: 16px 20px;

        .el-dialog__title {
          font-size: 16px;
        }
      }
    }
  }

  .form-container {
    padding: 20px;
    max-height: 60vh;
  }

  .account-form {
    :deep(.el-form-item__label) {
      font-size: 14px;
      width: 120px !important;
    }
  }

  .section-title {
    span {
      font-size: 15px;
    }
  }

  .auth-radio-group {
    .auth-radio {
      padding: 12px;
    }
  }

  .radio-content {
    .radio-text {
      .radio-desc {
        display: none;
      }
    }
  }

  .dialog-footer {
    padding: 16px 20px;

    .cancel-btn,
    .submit-btn {
      padding: 12px 16px;
      font-size: 14px;
    }
  }
}

@media (max-width: 480px) {
  .account-form-dialog {
    :deep(.el-dialog) {
      width: 100% !important;
      margin: 0;
      height: 100vh;
      border-radius: 0;
    }
  }

  .form-container {
    padding: 16px;
    max-height: calc(100vh - 140px);
  }

  .account-form {
    :deep(.el-form-item__label) {
      width: 100px !important;
      font-size: 13px;
    }
  }

  .form-section {
    margin-bottom: 24px;
  }

  .form-item {
    margin-bottom: 20px;
  }

  .auth-radio-group {
    gap: 12px;

    .auth-radio {
      padding: 10px;
    }
  }

  .radio-content {
    margin-left: 20px;

    .radio-icon {
      font-size: 18px;
    }
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;

    .cancel-btn,
    .submit-btn {
      width: 100%;
      justify-content: center;
    }
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .account-form-dialog {
    :deep(.el-dialog) {
      background: #1e293b;

      .el-dialog__body {
        background: #1e293b;
      }
    }
  }

  .form-container {
    background: #1e293b;
  }

  .section-title {
    border-color: #334155;

    span {
      color: #f1f5f9;
    }
  }

  .form-item {
    :deep(.el-form-item__label) {
      color: #e2e8f0;
    }
  }

  .auth-radio-group {
    .auth-radio {
      border-color: #334155;

      &:hover {
        background: #334155;
        border-color: #475569;
      }

      &.is-checked {
        background: rgba(0, 82, 204, 0.1);
      }
    }
  }

  .radio-content {
    .radio-text {
      .radio-label {
        color: #f1f5f9;
      }

      .radio-desc {
        color: #94a3b8;
      }
    }
  }

  .input-tip {
    background: #1e3a8a;
    border-color: #1e40af;

    span {
      color: #93c5fd;
    }

    &.warning {
      background: #451a03;
      border-color: #92400e;

      span {
        color: #fdba74;
      }
    }
  }

  .dialog-footer {
    background: #0f172a;
    border-color: #334155;
  }
}
</style>
